import 'package:flutter/material.dart';
import 'package:hockey/jzx_apps.dart';
import 'package:hockey/jzx_models.dart';
import 'package:hockey/services/jzx_config.dart';
import 'package:hockey/services/jzx_user.dart';
import 'package:hockey/widgets/dialogs/jzx_options_sheet.dart';

class JzxUserHomepageController extends GetxController {
  final uid = Get.parameters['uid'] ?? JzxUserService.to.uid;
  final author = Get.parameters['author'] ?? JzxUserService.to.author;

  var user = const JzxAuthorData().obs;
  var items = <JzxMediaData>[].obs;

  var isFollow = false.obs;

  @override
  void onInit() {
    super.onInit();
    isFollow.value = JzxConfigService.to.isFollow(uid);
    fetchData();
  }

  void fetchData() {
    // 用户所有的帖子
    user.value = JzxConfigService.to.findUserByUid(uid);
    items.value = JzxConfigService.to.getPostListByAuthor(author);
  }

  void showOptions() {
    Get.bottomSheet(
      JzxOptionsSheet(
        uid,
        onFollow: () {
          isFollow.toggle();
        },
        onBlock: () {
          isFollow.value = false;
        },
      ),
      backgroundColor: Colors.white,
      isScrollControlled: true,
      barrierColor: myAppColors.barrierColor,
    );
  }

  void likeOrCancel(JzxMediaData item, int index) {
    final state = item.isLiked;
    //
    if (state == false) {
      JzxUserService.to.updateUnlockConditions(2);
    }
    item = item.copyWith(
      isLiked: !state,
      like: item.like + (state ? -1 : 1),
    );
    items.value = List.of(items.value)..[index] = item;

    JzxConfigService.to.updatePostList(item, canRefresh: true);
  }

  void followAct() {
    JzxNetRepository.client.addFollow({'followUserId': uid});
    JzxConfigService.to.updateFollows(uid);
    showMessage(
        isFollow.value ? 'Unfollow Successfully' : 'Follow Successfully');

    isFollow.toggle();
  }
}
